package com.just.spring4.ch2.el;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;

/**
 * spring el表达式，支持在xml和注解中使用表达式，实现资源引入
 */
@Configuration
@ComponentScan("com.just.spring4.ch2.el")
@PropertySource(value = "classpath:com/just/spring4/ch2/el/test.properties")
public class ELConfig {
    @Value("I Love You!")                                   //注入普通字符串
    private String normal;
    @Value("#{systemProperties['os.name']}")                //注入操作系统属性
    private String osName;
    @Value("#{T(java.lang.Math).random()*100.0}")           //注入表达式结果
    private double randomNumber;
    @Value("#{demoServcie.another}")                        //注入其他bean属性
    private String fromAnother;
    @Value("classpath:com/just/spring4/ch2/el/test.txt")    //注入文件资源
    private Resource testFile;
    @Value("http://www.baidu.com")                          //注入网络资源
    private Resource testUrl;
    @Value("${book.name}")                                  //注入配置文件，注意，这个需要@PropertySource指定文件地址，并且配置PropertySourcesPlaceholderConfigurer 的Bean
    private String bookName;
    @Autowired
    private Environment environment;                        //从environment中也可以获取property
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigure(){
        PropertySourcesPlaceholderConfigurer placeholderConfigurer=new PropertySourcesPlaceholderConfigurer();
        placeholderConfigurer.setFileEncoding("UTF-8");
        return placeholderConfigurer;
    }
    public void outputResource(){
        try {
            System.out.println(normal);
            System.out.println(osName);
            System.out.println(randomNumber);
            System.out.println(fromAnother);
            System.out.println(testUrl);
            System.out.println("书名："+bookName);
            System.out.println("作者："+environment.getProperty("book.author"));
            System.out.println(IOUtils.toString(testFile.getInputStream()));
            System.out.println(IOUtils.toString(testUrl.getInputStream()));
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
